
/**
 * Created with IntelliJ IDEA.
 * User: laice
 * Date: 9/26/13
 * Time: 11:48 PM
 * To change this template use File | Settings | File Templates.
 */

var express = require('express'),
    app = express(),
    http = require('http'),
    serv = http.createServer(app).listen(8080),
    io = require('socket.io').listen(serv),
    phantom = require('node-phantom'),
    less = require('less'),
    infopunk = require('./infopunk.js'),
    opt = require('./local_config.js');

// for changing server "states"
var SERVER_MODE = 'base';



// for patching together broken
// pepper api calls
var pepper_first_half;

function server_mode(mode) {
    console.log("server mode set: " + mode);
    infopunk.server_mode = mode;
    SERVER_MODE = mode;

}
function update_page() {
    infopunk.update_css(infopunk.render());
}

io.set('log level', 0);
server_mode('current_match');
infopunk.set_url('www.saltybet.com')
infopunk.set_path('/state.json');

infopunk.update_css(infopunk.render());
var update_interval = setInterval(update_page, 5000);
infopunk.set_main_match();
infopunk.find_salt_logs();
infopunk.monitor_page();
//infopunk.get_name_dictionary();

function handle_data() {
    infopunk.get_data(infopunk.present_data);
    if(infopunk.new_data) {
        console.log("current data " + infopunk.new_data);
        infopunk.parse_salty_data(infopunk.new_data);
    }
    //if(infopunk.prev_data) console.log("prev data " + infopunk.prev_data);
}

function handle_action(){
    infopunk.do_action(infopunk.exec);
}

function get_heroku_app() {


    if(!infopunk.is_empty(infopunk.current_peppermill.p1.name) &&
        !infopunk.is_empty(infopunk.current_peppermill.p2.name)){

        var s = "http://fightmoney.herokuapp.com/stats/#/" +
            infopunk.current_peppermill.p1.name + "/" +
            infopunk.current_peppermill.p2.name + "/";

        console.log(s);


        var options = { phantomPath : PHANT_PATH};

        phantom.create(function(err,ph) {
            if(err)console.log(err);
            ph.createPage(function(err,page){
                if(err)console.log(err);
                console.log("in create page");
                page.open(s, function(err, status){
                    console.log("phantom status: " + status);
                    page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function(err) {


                        console.log("load status" + status) ;


                        page.evaluate(function() {
                            var comments_p1 = [], comments_p2 = [], tags_p1 = [], tags_p2 = [];
                            var loss_p1 = [], loss_p2 = [], win_p1 = [], win_p2 = [];
                            //console.log($('body'));
                            // use jquery to find each comment block and return it
                            $('#p_one_data').find('.comments').find("li").each(function(){
                                comments_p1.push($(this).html());
                            });

                            $('#p_one_data').find('.history').find(".loss").each(function(){
                                loss_p1.push($(this).html());
                            });

                            $('#p_one_data').find('.history').find('.win').each(function(){
                                win_p1.push($(this).html());
                            });

                            $('#p_two_data').find('.comments').find("li").each(function(){
                                comments_p2.push($(this).html());
                            });

                            $('#p_two_data').find('.history').find('.loss').each(function(){
                                loss_p2.push($(this).html());
                            });

                            $('#p_two_data').find('.history').find('.win').each(function(){
                                win_p2.push($(this).html());
                            });

                            $('#p_one_data').find('.tags').find("li").each(function(){

                                console.log('found p1 tag');
                                tags_p1.push($(this).html());
                            })

                            $('#p_two_data').find('.tags').find("li").each(function(){

                                console.log('found p2 tag');
                                tags_p2.push($(this).html());
                            })



                            return { comments_p1: comments_p1, loss_p1: loss_p1,
                                win_p1 : win_p1, comments_p2 : comments_p2,
                                loss_p2 : loss_p2, win_p2 : win_p2,
                                tags_p1 : tags_p1, tags_p2 :tags_p2};
                        }, function(err, result){
                           //console.log("js data: ");
                            //console.log(result);

                            infopunk.parse_heroku_app(result);

                            ph.exit();
                        });


                    }, 3000);
                });
            });

        }, options );

        /*
        http.get(s, function(res){
            res.setEncoding('utf8');
            res.on('data', function(data){
                console.log(data);
            });
        });
        */

    }
}

exports.roundly = function() {
    infopunk.losses.p1 = {};
    infopunk.losses.p2 = {};
    infopunk.wins.p1 = {};
    infopunk.wins.p2 = {};
    infopunk.fetched_elo = false;
    infopunk.p1_elo_sent = false;
    infopunk.p2_elo_sent = false;
    infopunk.match_logged = false;

}



exports.send_elo = function(player, pos){

    var el;

    switch(player){
        case 1:
            el = infopunk.elos.p1;
            break;
        case 2:
            el = infopunk.elos.p2;
            break;
        default:
            break;

    }

    el = JSON.stringify(el);

    var tuco = "" + player + " " + pos;




    for(var i in infopunk.client_sockets){
        infopunk.client_sockets[i].emit(tuco, {elos : el, type : tuco} );
    }




}

function get_fight_money_player(player_id){

    http.get("http://www.hightower-software.com/ss/api/players/" + player_id, function(res){

        res.on('data', function(data){
            console.log("fight money data: " + data);

            infopunk.current_fm_player = data;

        });

    }).on('error', function(e){if(e) console.log(e);});


}

function get_peppermill_player(player_id){

    http.get("http://www.apeppershaker.com/api/champions/" + player_id, function(res){

        res.on('data', function(data){
            console.log("peppermill data: " + data);

            infopunk.current_pm_player = data;

        });

    }).on('error', function(e){if(e) console.log(e);});

}

exports.get_player_wins = function(player, pos){
    var request = require('request');

    var s = "http://www.apeppershaker.com/api/champions/" + player + "/wins";
    
    var ids = [];

    request(s, function(error, res, body){
        if(!error && res.statusCode == 200){
            console.log('pshaker ' + player + ' win : ' + body );
            if(pos == 1) {
                infopunk.wins.p1 = JSON.parse(body);
                console.log('infpunk.wins.p1 : ' + JSON.stringify(infopunk.wins.p1));
                for(var i in infopunk.wins.p1.fights){

                    //console.log(JSON.stringify(infopunk.wins.p1.fights[i]));


                    if(infopunk.wins.p1.fights[i].winner == 1){
                        ids.push(infopunk.wins.p1.fights[i].blue_champion_id);
                    } else if (infopunk.wins.p1.fights[i].winner == 2){
                        ids.push(infopunk.wins.p1.fights[i].red_champion_id);
                    }

                }

                infopunk.get_fought_elo(ids, 1, "win");

            } else if ( pos == 2){
                infopunk.wins.p2 = JSON.parse(body);
                for(var i in infopunk.wins.p2.fights){
                    if(infopunk.wins.p2.fights[i].winner == 1){
                        ids.push(infopunk.wins.p2.fights[i].blue_champion_id);
                    } else if (infopunk.wins.p2.fights[i].winner == 2){
                        ids.push(infopunk.wins.p2.fights[i].red_champion_id);
                    }
                }

                infopunk.get_fought_elo(ids, 2, "win");
                
            }
            
            
            

        }
    });
}

exports.get_player_losses = function(player, pos){
    var request = require('request');

    var s = "http://www.apeppershaker.com/api/champions/" + player + "/losses";

    var ids = [];

    request(s, function(error, res, body){
        if(!error && res.statusCode == 200){
            console.log('pshaker ' + player + ' loss : ' + body );
            if(pos == 1) {
                infopunk.losses.p1 = JSON.parse(body);
                for(var i in infopunk.losses.p1.fights){
                    if(infopunk.losses.p1.fights[i].winner == 1){
                        ids.push(infopunk.losses.p1.fights[i].red_champion_id);
                    } else if (infopunk.losses.p1.fights[i].winner == 2){
                        ids.push(infopunk.losses.p1.fights[i].blue_champion_id);
                    }
                }

                infopunk.get_fought_elo(ids, pos, "loss");

            } else if ( pos == 2){
                infopunk.losses.p2 = JSON.parse(body);
                for(var i in infopunk.losses.p2.fights){
                    if(infopunk.losses.p2.fights[i].winner == 1){
                        ids.push(infopunk.losses.p2.fights[i].red_champion_id);
                    } else if (infopunk.losses.p2.fights[i].winner == 2){
                        ids.push(infopunk.losses.p2.fights[i].blue_champion_id);
                    }
                }

                infopunk.get_fought_elo(ids, pos, "loss");

            }
        }
    });
}

function get_pepper_shaker() {
    var s = "http://apeppershaker.com/api/fights/by_id/" +
        infopunk.current_peppermill.p1.id + "/" +
        infopunk.current_peppermill.p2.id + "/";

    console.log("id1 : " + infopunk.current_peppermill.p1.id +
            " id2 : " + infopunk.current_peppermill.p2.id);
    if(!infopunk.is_empty(infopunk.current_peppermill.p1.id) &&
        !infopunk.is_empty(infopunk.current_peppermill.p2.id)) {
        http.get(s, function(res){
            res.setEncoding('utf8');
            res.on('data', function(data) {
                //console.log("pepper api :" + data);

                var is_full = data.substring(data.length-1);
                var full_string;


                if (is_full != "}") {
                    console.log("fragmented pepper request, patching..")
                    pepper_first_half = data;
                    return;
                } else {
                    if(!infopunk.is_empty(pepper_first_half)) {
                        full_string = pepper_first_half + data;
                    } else {
                        full_string = data;
                    }
                }

                if(!infopunk.is_empty(full_string)) {
                   // console.log("full pepper string: " + full_string);

                    infopunk.parse_fight_json(full_string);
                }




            });
        });
    }
}

data_interval = setInterval(handle_data, infopunk.data_interval);
action_interval = setInterval(handle_action, infopunk.action_interval);


app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", { layout: false });
app.configure(function(){
   app.use(express.static(__dirname + '/public'));
});

app.get('/', function(req, resp) {
    if(infopunk.mrt.home){
        resp.send(infopunk.mrt.home);
    }

    if (SERVER_MODE == "current_match") {
        // will want to change this to only send to
        // the connectee in the future, currently
        // emits to all socket connections
        exports.teaser_match();
    }
});
//app.listen(8080);



io.sockets.on('connection', function(socket) {
    console.log("connection activity...");
    socket.on('mode', function(data) {
        console.log('client initiated mode change');
        server_mode(data.mode);
        infopunk.set_main_match();

    });

    socket.on('new_client', function() {
        console.log('new client');
        var len = infopunk.client_sockets.length;
        infopunk.client_sockets[len] = socket;
        infopunk.client_ids = len;
        socket.emit('your_id', { id : len});

    });

    socket.on('debug', function(data) {
        console.log(data.output);
    });

    socket.on('p1_win_elo', function(data){

        var s = JSON.stringify(infopunk.elos.p1.wins);

        console.log('p1 wins: ' + s);

        socket.emit('p1_win_elo', { elos : s });

    });

    socket.on('p1_loss_elo', function(data){

        var s = JSON.stringify(infopunk.elos.p1.losses);

        console.log('p1 losses: ' + s);
        socket.emit('p1_loss_elo', { elos : s });

    });

    socket.on('p2_win_elo', function(data){

        var s = JSON.stringify(infopunk.elos.p2.wins);

        console.log('p2 wins: ' + s);

        socket.emit('p2_win_elo', { elos : s });

    });

    socket.on('p2_loss_elo', function(data){

        var s = JSON.stringify(infopunk.elos.p2.losses);

        console.log('p2 losses: ' + s);

        socket.emit('p2_loss_elo', { elos : s });

    });






    /*
    socket.on('setPseudo', function(data) {
        socket.set('pseudo', data);
    });

    socket.on('message', function(message) {
        socket.get('pseudo', function(error, name) {
            var data = { 'message' : message, pseudo : name };
            socket.broadcast.emit('message', data);
            console.log("user " + name + " send this : " + message);
        })

    });
      */


});

exports.get_server_mode = function(){
    console.log("server mode : " + SERVER_MODE);
    return SERVER_MODE;
}

exports.match_status = function(status) {
    console.log("emitting match status");



    for(var i in infopunk.client_sockets){
        infopunk.client_sockets[i].emit('match_status', { status : status });
    }
}


exports.teaser_match = function() {
    console.log("emitting teaser");
    var data = JSON.stringify(infopunk.current_peppermill)

    for(var i in infopunk.client_sockets){
        infopunk.client_sockets[i].emit('teaser',{ data : data});
    }

    if(infopunk.match_logged == false){
        get_pepper_shaker();
        get_heroku_app();
        infopunk.match_logged = true;
    }

}

exports.attr_match = function() {
    console.log("emitting attr");
    var data = JSON.stringify(infopunk.attributes);

    for(var i in infopunk.client_sockets){
        infopunk.client_sockets[i].emit('attr', { data : data});
    }
}

exports.log_match = function() {
    if(!infopunk.is_empty(infopunk.comments.p1)){
        var s = JSON.stringify(infopunk.comments.p1);
        for(var i in infopunk.client_sockets){
            infopunk.client_sockets[i].emit('p1_comm',{ comments : s});
        }
    }

    if(!infopunk.is_empty(infopunk.comments.p2)){
        var s = JSON.stringify(infopunk.comments.p2);
        for(var i in infopunk.client_sockets){
            infopunk.client_sockets[i].emit('p2_comm',{ comments : s});
        }
    }

    if(!infopunk.is_empty(infopunk.loss_log.p1)){
        var s = JSON.stringify(infopunk.loss_log.p1);
        for(var i in infopunk.client_sockets){
            infopunk.client_sockets[i].emit('p1_loss',{ loss : s});
        }

    }

    if(!infopunk.is_empty(infopunk.loss_log.p2)){
        var s = JSON.stringify(infopunk.loss_log.p2);
        for(var i in infopunk.client_sockets){
            infopunk.client_sockets[i].emit('p2_loss',{ loss : s});
        }
    }

    if(!infopunk.is_empty(infopunk.win_log.p1)){
        var s = JSON.stringify(infopunk.win_log.p1);
        for(var i in infopunk.client_sockets){
            infopunk.client_sockets[i].emit('p1_win',{ win : s});
        }
    }

    if(!infopunk.is_empty(infopunk.win_log.p2)){
        var s = JSON.stringify(infopunk.win_log.p2);
        for(var i in infopunk.client_sockets){
            infopunk.client_sockets[i].emit('p2_win',{ win : s});
        }
    }

    if(!infopunk.is_empty(infopunk.tags.p1)){
        console.log('in p1 tags') ;
        var s = JSON.stringify(infopunk.tags.p1);
        for(var i in infopunk.client_sockets){
            infopunk.client_sockets[i].emit('p1_tags', {tags : s});
        }
    }

    if(!infopunk.is_empty(infopunk.tags.p2)){
        console.log('in p2 tags');
        var s = JSON.stringify(infopunk.tags.p2);
        for(var i in infopunk.client_sockets){
            infopunk.client_sockets[i].emit('p2_tags', {tags : s});
        }
    }
}





